package org.swxjava.assembler.avm1.convert;

import java.lang.reflect.Array;

import org.swxjava.assembler.Converter;
import org.swxjava.assembler.MarshallException;
import org.swxjava.assembler.ObjectCompiler;
import org.swxjava.assembler.avm1.AsArray;
import org.swxjava.assembler.avm1.AsArrayElement;
import org.swxjava.util.ArrayUtils;
import org.swxjava.util.Log;
import org.swxjava.util.LogFactory;

public class ArrayConverter extends BaseConverter implements Converter {
	/**
	 * The log stream
	 */
	private static final Log LOG = LogFactory.getLog(ArrayConverter.class);

	public ObjectCompiler convert(Object data)
			throws MarshallException {
		if (!data.getClass().isArray()) {
			throw new MarshallException(data.getClass());
		}

		// Convert all the data members
		int size = ArrayUtils.getLength(data);

		AsArray array = new AsArray();
		for (int i = (size-1); i >= 0; i--) {
			Object member = Array.get(data, i);
			ObjectCompiler value;
			try {
				value = config.convert(member);
			} catch (Exception ex) {
				value = config.convert(null);
				LOG.warn("Failed to convert array member " + i
						+ ". Conversion error for type: "
						+ data.getClass().getName(), ex);
			}
			AsArrayElement element = new AsArrayElement(i, value);
			array.add(element);
		}
		return array;
	}

}
